package toy.keli.edic.data.model

import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.mlkit.vision.common.InputImage
import toy.keli.edic.MainActivity
import toy.keli.edic.data.Db
import toy.keli.edic.data.config.PathConf
import toy.keli.edic.data.local.entity.BookItemIcoEntity
import toy.keli.edic.ui.main.extend.date
import toy.keli.edic.ui.main.extend.toByteArray
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.util.FileUtil
import toy.keli.edic.util.MediaUtil
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.jar.Manifest

/**
 * 书本条目的公共方法
 */
interface BookItemMethods {
    fun hasIco(cid:Int): Boolean{
        val ctype = this.javaClass.simpleName
        Db.user.apply {
            val query = ico.find().select("name,ctype,cid,id").where("ctype", ctype).andWhere("cid", cid).build()
            val icoModel = ico.select(query).firstOrNull()
            return icoModel!=null
        }
    }

    fun addIco(img: InputImage, id: Int) {
        val ctype = this.javaClass.simpleName
        if(img.width>200){
            val time = date("MMddHHmm")
            val file = PathConf.dcim+"ico_${ctype}_${id}_${time}.png"
            Db.user.ico.add(BookItemIcoEntity(id,ctype,file))
            MediaUtil.saveImageToDCIM(ActivityRun.context,img.bitmapInternal!!,file.substring(PathConf.dcim.length));
        }else {
             Db.user.ico.add(BookItemIcoEntity(id,ctype,"",img.bitmapInternal.toByteArray()))
        }
    }

    fun getIco(id:Int): Bitmap? {
        val ctype = this.javaClass.simpleName
        Db.user.apply {
            val query = ico.find().where("ctype",ctype).where("cid",id).build()
            val icoModel = ico.select(query).first()
            return if(icoModel.name.length>0) {
                val uri = MediaUtil.getImageUriByPath(ActivityRun.context,icoModel.name)
                if(uri!=null) {
                    MediaUtil.loadImageFromUri(ActivityRun.context, uri)
                }else{
                    null
                }
//                BitmapFactory.decodeFile(icoModel.name)
            }else
                BitmapFactory.decodeByteArray(icoModel.content,0,icoModel.content!!.size)
        }
    }
}
